package com.h5;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyz.domain.CateRecommend;
import com.demo.domain.Code;
import com.demo.domain.Focus;
import com.demo.mobile.MobException;
import com.demo.util.DateUtil;
import com.demo.util.JSONUtils;
import com.h5.util.GB2Alpha;
import com.shopcart.domain.StoreCategory;
import com.shopcart.service.QuickShoppingService;
import com.vsd.daoEx.model.IndexActStoreEx;
import com.vsd.domain.City;
import com.vsd.domain.IndexActivity;
import com.vsd.repository.CateRecommendRepository;
import com.vsd.repository.CityRepository;
import com.vsd.repository.IndexActivityRepository;
import com.vsd.repository.StoreCategoryRepository;
import com.vsd.service.CityService;
import com.vsd.service.CodeService;
import com.vsd.service.FocusService;
import com.vsd.service.IndexActGoodsService;
import com.vsd.service.IndexActStoreService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StoreService;
import com.zy.order.proto.MSOrder.MMiniGoods;
import com.zy.order.proto.MSOrder.MMiniGoodsList;
import com.zy.sys.proto.MOCommon.MCity;
import com.zy.sys.proto.MOCommon.MCityList;

@RequestMapping("/m/i")
@Controller
public class IndexController extends H5BaseController {
	@Autowired
	CateRecommendRepository cateRecommendRepository;
	@Autowired
	StoreCategoryRepository storeCategoryRepository;
	@Autowired
	IndexActivityRepository indexActivityRepository;
	@Autowired
	StoreService storeService;
	@Autowired
	IndexActStoreService indexActStoreService;
	@Autowired
	IndexActGoodsService indexActGoodsService;
	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	CityService cityService;
	@Autowired
	FocusService focusService;
	@Autowired
	QuickShoppingService quickShoppingService;
	@Autowired
	CodeService codeService;
	@Autowired
	CityRepository cityRepository;

	@RequestMapping("/cateList")
	@ResponseBody
	public String category(String areaCode, Integer location) {
		if (location == null) location = 1;
		if (location == 1) {
			Page<CateRecommend> recommend = cateRecommendRepository
					.findByAreaCode(areaCode, new PageRequest(0, 7, new Sort(
							Direction.DESC, "sort")));
			return JSONUtils.serialize(recommend.getContent());
		} else if (location == 2) {
			Collection<StoreCategory> list = storeCategoryRepository
					.findByLevel(1,new Sort(Direction.DESC, "sort"));
			return com.demo.util.JSONUtils.serialize(list);
		}
		return JSONUtils.serialize(null);
	}

	@RequestMapping("/activity")
	@ResponseBody
	public String activitys(String areaCode, Integer location) {
		Page<IndexActivity> list = indexActivityRepository.findByAreaCodeAndState(
				areaCode,1, new PageRequest(0, 5, new Sort(Direction.DESC,
						"sortOrder")));
		return JSONUtils.serialize(list);
	}

	@RequestMapping("/actStore")
	@ResponseBody
	public String actStoreList(String id, String lng, String lat, Integer page,
			Integer limit) {
		Collection<IndexActStoreEx> list = indexActStoreService.selectAppList(
				id, lng, lat, page, limit);
		return JSONUtils.serialize(list);
	}

	@RequestMapping("/actGoods")
	@ResponseBody
	public String actTg(String lat, String lng, String id, Integer page,
			Integer limit) {
		String sql = "select sg.id as goodsId,sg.`name` as goodsName,sg.img,sg.now_price,sg.sell_base	,s.`name` as storeName ";

		if (StringUtils.isNoneBlank(lat) && StringUtils.isNoneBlank(lng)) {
			sql += ",getDistance(s.lng,s.lat," + lng + "," + lat
					+ ") as distance";
		}

		sql += "	,(select count(1) from s_order o where o.store_id = s.id and o.state=4) as sellCnt"
				+ "	from f_index_act_goods ag  left join s_store_goods sg on ag.gid = sg.id"
				+ "	left join s_store s on s.id = sg.store_id"
				+ "	where s.is_online=1 and s.closed=0 and sg.is_online=1 and sg.is_del=0 and ag.act_id = '"
				+ id
				+ "' order by sort_order desc"
				+ " limit "
				+ page
				* limit
				+ "," + (page + 1) * limit;

		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);

		return JSONUtils.serialize(maps);
	}

	@RequestMapping("/guess")
	@ResponseBody
	public String guess(String lat, String lng) {
		String sql = "select sg.id as goodsId,sg.`name` as goodsName,sg.img,sg.now_price,sg.sell_base	,s.`name` as storeName ";

		if (StringUtils.isNoneBlank(lat) && StringUtils.isNoneBlank(lng)) {
			sql += ",getDistance(s.lng,s.lat," + lng + "," + lat
					+ ") as distance";
		}

		sql += "	,(select count(1) from s_order o where o.store_id = s.id and o.state=4) as sellCnt"
				+ "	from  s_store_goods sg "
				+ "	left join s_store s on s.id = sg.store_id"
				+ "	where s.is_online=1 and s.closed=0 and sg.is_online=1 and sg.is_del=0   order by rand()"
				+ " limit 0,20";
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		return JSONUtils.serialize(maps);
	}
	
	@RequestMapping(value="cityMatch", method = RequestMethod.POST)
	@ResponseBody
    public String cityMatch(String name){
		// 参数校验
		if (StringUtils.isBlank(name)) {
			return JSONUtils.serialize(new Ret(-1));
		}
		City city = cityService.findByNameAndState(name);
		
		Ret ret = new Ret();
		ret.setCode(0);
		ret.setData("001,常州市");
		if(city != null){
			ret.setData(city.getCode()+","+city.getName());
		}else{
			city = cityService.findDefault();
			ret.setData(city.getCode()+","+city.getName());
		}
		return JSONUtils.serialize(ret);
	}
	
	@RequestMapping("/focusList")
	@ResponseBody
	public String focusList(String restraint,Integer location){
		if(location==null) location = 1;
		Page<Focus> focus = null;
		Sort sort = new Sort(Direction.DESC, "sort");
		Pageable p = new PageRequest(0, 5,sort);
		if(StringUtils.isNotBlank(restraint)){
			focus = focusService.findByLocationAndRestraint(location, restraint,p);
		}else{
			focus = focusService.findByLocation(location,p);
		}
		return JSONUtils.serialize(focus);
	}
	
	
	@RequestMapping("/quickshopping")
	@ResponseBody
	public String quick(String areaCode){
		JSONObject object = new JSONObject();
		JSONArray titles = new JSONArray();
		List<String> periods = quickShoppingService.selectTodayPriod(areaCode);
		if(periods.size()>0){
			Date now = new Date();
			Integer code = codeService.getQuickTime();//持续分钟数
			if(now.getHours() == Integer.parseInt(periods.get(0)) && now.getMinutes()>=code){
				periods.remove(0);
			}
			
			if(periods.size()>0){
				object.put("title", periods);
				Date begin = DateUtil.strToDate(DateUtil.asShortString(now)+" "+periods.get(0)+":00:00", "yyyy-MM-dd HH:mm:ss");
				int sec = (int)(begin.getTime()/1000 - now.getTime()/1000);
				object.put("seconds", sec);
				object.put("minutes", sec);
				 
//				List<String> list = quickShoppingService.selectGoodsImg(periods.get(0), areaCode);
//				object.put("imgs", list);
			}
		}
		Code c = codeService.findOne("rebate@sys");
		if(c!=null) object.put("imgs",new String[]{c.getValue()});
		return JSONUtils.serialize(object);
	}
	
	@RequestMapping("/quickGoodsList")
	@ResponseBody
	public String mQuickGoodsList(String areaCode,String type,Integer page,Integer limit) throws Exception {
		if (StringUtils.isBlank(type)) {throw new MobException("type");}
		MMiniGoodsList.Builder goodsList = quickShoppingService.selectPeriodGoods(type,areaCode);
		JSONArray ret = new JSONArray();
		for (MMiniGoods.Builder mini : goodsList.getListBuilderList()){
			JSONObject m = new JSONObject();
			m.put("id", mini.getId());
			m.put("name", mini.getTitle());
			m.put("price", mini.getPrice());
			ret.add(m);
		}
		return JSONUtils.serialize(ret);
	}
	
//	@RequestMapping("/cityList")
//	@ResponseBody
//	public String cityList() throws Exception {
//		Collection<City> list = cityRepository.findByLevelAndState(1, 1,new Sort(Direction.DESC, "sort"));
//		JSONObject ret = new JSONObject();
//		ret.put("pinyinList", list);
//		return ret.toString();
//	}
	
	/**
	@RequestMapping(value="getCityName", method = RequestMethod.POST)
	@ResponseBody
    public String getCityName(String code){
		// 参数校验
		if (StringUtils.isBlank(code)) {
			return JSONUtils.serialize(new Ret(-1));
		}
		
		CityExample example = new CityExample();
		example.createCriteria().andStatusEqualTo(1).andCodeEqualTo(code);
		List<City> list = cityService.selectByExample(example);
		
		Ret ret = new Ret();
		ret.setCode(0);
		ret.setMsg("0,全国");
		if(list.size()>0){
			ret.setMsg(list.get(0).getCode()+","+list.get(0).getName());
		}
		return JSONUtils.serialize(ret);
	}*/
	
	@RequestMapping("/cityList")
	@ResponseBody
	public String cityList(Integer location,String parent){
		if(location==null) location=1;
		MCityList.Builder c = cityService.selectByLocation(location,parent);
		JSONArray ret = new JSONArray();
		JSONArray hot = new JSONArray();
		GB2Alpha util = new GB2Alpha();  
		Set<String> set = new TreeSet<String>();
		for(MCity.Builder mini : c.getListBuilderList()){
			JSONObject m = new JSONObject();
			m.put("code", mini.getCode());
			m.put("name", mini.getName());
			m.put("account", util.String2Alpha(mini.getName()));
			ret.add(m);
			if (mini.getHot() == 1){
				hot.add(m);
			}
			set.add(util.String2Alpha(mini.getName()).substring(0,1));
		}
		
		List<JSONObject> pinyin = new ArrayList<JSONObject>();
		for (String x : set) {
			JSONObject obj = new JSONObject();
			obj.put("pinyin", x);
			JSONArray array = new JSONArray();
			for (int i = 0; i < ret.size(); i++){
				if (ret.getJSONObject(i).getString("account").startsWith(x)){
					array.add(ret.getJSONObject(i));
				}
			}
			obj.put("list", array);
			pinyin.add(obj);
		}
		
		JSONObject obj = new JSONObject();
		obj.put("hotList", hot);
		obj.put("pinyinList", pinyin);
		
		return JSONUtils.serialize(obj);
	}
}
